package com.transport.dao;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.classic.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.transport.model.Word;
import com.transport.utils.PageSet;

public class WordDao extends HibernateDaoSupport{

	public Map queryWordList(PageSet pageSet) {
		Map map = new HashMap();
		String sql = "select count(*) from Word";
		Long total = (Long) getHibernateTemplate().find(sql).get(0);
		Session session = getHibernateTemplate().getSessionFactory().openSession();
		Query q = session.createQuery("from Word");
		q.setFirstResult((pageSet.getPage() - 1) * pageSet.getRows());
		q.setMaxResults(pageSet.getRows());
		List list = q.list();
		map.put("total", total);
		map.put("rows", list);
		session.close();
		return map;
	}

	public String checkExist(Word word) {
		List list = getHibernateTemplate().find(
				"from Word where title='" +word.getTitle() + "'");
		if (list.size() == 0) {
			return "none";
		}
		else {
			return "one";
		}
	}

	public String addWord(Word word) {
		word.setCreatedate(new Date());
		getHibernateTemplate().save(word);
		return "success";
	}

	public void deleteWord(String id) {
		getHibernateTemplate().delete(getHibernateTemplate().find("from Word where id="+id).get(0));
	}

	public Word queryWordById(String id) {
		return (Word)getHibernateTemplate().find("from Word where id="+id).get(0);
	}

	public String updateWord(Word word) {
		if(word!=null){
			getHibernateTemplate().saveOrUpdate(word);
		}
		else{
			return "error";
		}
		return "success";
	}

}
